import React, { Component } from 'react';
import { getMultiLang, createPage, cardCache, toast, viewModel } from 'nc-lightapp-front';
import Inspection from 'epmp/exports/components/Inspection';
import LinkQueryFyytModel from 'ssccommon/linkquery/LinkQueryFyytModel';
import LinkQueryFysqModel from 'ssccommon/linkquery/LinkQueryFysqModel';
import LinkQueryJkbxModel from 'ssccommon/linkquery/LinkQueryJkbxModel';
import ApproveDetail from 'uap/common/components/ApproveDetail';
import _ from 'lodash-es';
import config from './config';
import { onSearchButtonClick, onPageButtonClick, onTablePageChange, onTableSelectChange } from './events';
import api from '../../common/api';

const { setGlobalStorage, getGlobalStorage, removeGlobalStorage } = viewModel;
const { setDefData, getDefData } = cardCache;

class Page extends Component {
    constructor(props) {
        super(props);
        props.use.search(config.headcode);
        props.use.table(config.bodycode);
        this.state = {
            multiLang: {},
            isInspectionShowed: false,
            inspectionSourceData: {},
            // 联查费用申请单
            isLinkQueryFysqModelShowed: false,
            linkQueryFysqModelSourceData: {},
            // 联查费用预提单
            isLinkQueryFyytModelShowed: false,
            linkQueryFyytModelSourceData: {},
            // 联查借款单
            isLinkQueryJkbxModelShowed: false,
            linkQueryJkbxModelSourceData: { tradetype: '' },
            // 联查审批情况
            isApproveDetailShowed: false,
            approveDetailSourceData: {}
        };
        // TODO 缓存多语
    }

    componentDidMount() {
        this.initTempAndLang();
    }

    initTempAndLang() {
        const props = this.props;
        getMultiLang({
            ...config.multiLang,
            callback: json => {
                this.setState({ multiLang: json }, () => {
                    props.createUIDom({ pagecode: config.pagecode }, data => {
                        console.log('=====template', data);
                        this.setButton(data.button);
                        this.setMeta(data.template, data.button);
                    });
                });
            }
        });
    }

    setMeta(meta, button) {
        const props = this.props;
        // const { setPageStatus } = this.props;
        // meta[config.bodycode].status = 'browse';
        // setDefData(`${config.headcode}_oid`, config.dataSource, meta[config.headcode].oid);

        meta[config.headcode].items.forEach(item => {
            if (item.attrcode === 'pk_tradetypeid') {
                item.queryCondition = function () {
                    return {
                        GridRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.ErmTranstypeRefSqlBuilder'
                    };
                };
            } else if (item.attrcode === 'pk_org') {
                item.queryCondition = function () {
                    return {
                        TreeRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.OrgTreeRefSqlBuilder',
                        DataPowerOperationCode: 'fi',
                        isDataPowerEnable: 'Y'
                    };
                };
            }
        });

        meta[config.bodycode].pagination = true;
        meta[config.bodycode].pageInfo = {
            pageSize: config.pageSize
        };

        props.meta.setMeta(meta, () => {
            this.initPage();
        });
    }

    setButton(button) {
        const props = this.props;
        props.button.setButtons(button);
    }

    initPage() {
        const props = this.props;
        props.table.setTableRender(config.bodycode, 'djbh', (text, record) => {
            return (
                <a
                    // className="hyperlinks"
                    onClick={() => {
                        api.getBillLinkInfo({
                            openbillid: _.get(record, 'pk_jkbx.value'),
                            tradetype: _.get(record, 'djlxbm.value'),
                            sence: '3'
                        }).then(res => {
                            if (!res || !res.url) {
                                toast({
                                    color: 'warning',
                                    content: this.state.multiLang['bad_request']
                                }); /* 国际化处理： 参数错误*/
                                return;
                            }
                            props.specialOpenTo(res.url, {
                                status: 'browse',
                                id: res.openbillid,
                                tradetype: res.tradetype,
                                appcode: res.appcode,
                                pagecode: res.pagecode,
                                scene: 'bzcx'
                            });
                        });
                    }}
                >
                    {_.get(record, 'djbh.value')}
                </a>
            );
        });
        this.setPageStatus();

        props.search.setSearchValByField(config.headcode, 'djrq', {
            display: '今日~今日',
            value: '#day(0)#,#day(0)#'
        });

        // try {
        //    const searchVal = JSON.parse(getGlobalStorage('sessionStorage', config.searchCache));
        //    if (searchVal && searchVal.conditions) {
        //        this.props.search.setSearchValue(config.headcode, searchVal);
        //        this.loadData(searchVal, true);
        //    }
        // } catch (error) {
        //    console.log(error);
        // }

        // if (!getDefData('pk_org', config.dataSourceCommon)) {
        //     api.getUserInfo().then((data) => {
        //         setDefData('pk_org', config.dataSourceCommon, data.pk_org);
        //     });
        // }
    }

    setPageStatus() {
        const props = this.props;
        props.button.setButtonDisabled(['link', 'print'], true);
        props.table.selectAllRows(config.bodycode, false);
    }

    loadData(isFromSearch) {
        const props = this.props;
        const meta = props.meta.getMeta();
        const pageInfo = props.table.getTablePageInfo(config.bodycode);
        const query = props.search.getAllSearchData(config.headcode);

        const params = {
            appcode: config.appcode,
            pagecode: config.pagecode,
            queryAreaCode: config.headcode,
            querytype: 'tree',
            querycondition: query,
            oid: meta[config.headcode].oid,
            pageInfo: {
                pageIndex: pageInfo.pageIndex,
                pageSize: isFromSearch ? config.pageSize : pageInfo.pageSize
            }
        };

        return api.getBillList(params).then(res => {
            // 按钮初始化
            if (isFromSearch) {
                const total = Number(_.get(res, 'pageInfo.total', 0));
                if (total === 0) {
                    toast({
                        color: 'warning',
                        content: this.state.multiLang['query_none_message']
                    }); /* 国际化处理： 未查询出符合条件的数据*/
                } else {
                    toast({
                        color: 'success',
                        content: this.state.multiLang['query_total_message'].replace('{count}', total)
                    }); /* 国际化处理： 查询成功，共*条*/
                }
            } else {
                toast({
                    color: 'success',
                    content: this.state.multiLang['query_success']
                }); /* 国际化处理： 查询成功*/
            }

            this.setData(res);
        });
    }

    setData(res) {
        const props = this.props;
        const pageInfo = _.get(res, `pageInfo`, {});
        const data = {
            rows: _.get(res, `data.${config.bodycode}.rows`, []),
            pageInfo: pageInfo
        };
        if (pageInfo.pageIndex == 0) {
            data.allpks = new Array(Number(pageInfo.total));
        }
        props.table.setAllTableData(config.bodycode, data);
    }

    render() {
        const { table, button, search, modal, BillHeadInfo } = this.props;
        const { NCCreateSearch } = search;
        const { createBillHeadInfo } = BillHeadInfo;
        const { createSimpleTable } = table;

        return (
            <div className="nc-single-table">
                <div className="nc-singleTable-header-area">
                    <div className="header-title-search-area">
                        {createBillHeadInfo({
                            title: this.state.multiLang['query_page_title'],
                            initShowBackBtn: false
                        })}
                    </div>
                    <div className="header-button-area">
                        {button.createButtonApp({
                            area: config.pageButtonArea,
                            buttonLimit: 8,
                            onButtonClick: onPageButtonClick.bind(this)
                        })}
                    </div>
                </div>
                <div className="nc-singleTable-search-area">
                    {NCCreateSearch(config.headcode, { clickSearchBtn: onSearchButtonClick.bind(this) })}
                </div>
                <div className="nc-singleTable-table-area">
                    {createSimpleTable(config.bodycode, {
                        handlePageInfoChange: onTablePageChange.bind(this),
                        selectedChange: onTableSelectChange.bind(this),
                        showIndex: true,
                        showCheck: true
                    })}
                </div>

                {/* 联查预算 */}
                {this.state.isInspectionShowed && (
                    <Inspection
                        show={this.state.isInspectionShowed}
                        sourceData={this.state.inspectionSourceData}
                        cancel={() => this.setState({ isInspectionShowed: false })}
                        affirm={() => this.setState({ isInspectionShowed: true })}
                    />
                )}

                {/* 联查费用申请单 */}
                <LinkQueryFysqModel
                    show={this.state.isLinkQueryFysqModelShowed}
                    close={() => this.setState({ isLinkQueryFysqModelShowed: false })}
                    // linkData={this.state.linkData}
                    // tradetype={window.presetVar.tradetype}
                    // openBillId={this.state.billId}
                    {...this.state.linkQueryFysqModelSourceData}
                    {...this.props}
                />

                {/* 联查费用预提单 */}
                <LinkQueryFyytModel
                    show={this.state.isLinkQueryFyytModelShowed}
                    close={() => this.setState({ isLinkQueryFyytModelShowed: false })}
                    // linkData={this.state.linkData}
                    // tradetype={window.presetVar.tradetype}
                    // openBillId={this.state.billId}
                    {...this.props}
                    {...this.state.linkQueryFyytModelSourceData}
                />

                {/* 联查借款单 */}
                <LinkQueryJkbxModel
                    show={this.state.isLinkQueryJkbxModelShowed}
                    close={() => this.setState({ isLinkQueryJkbxModelShowed: false })}
                    // linkData={this.state.linkData}
                    // tradetype={window.presetVar.tradetype}
                    // openBillId={this.state.billId}
                    {...this.state.linkQueryJkbxModelSourceData}
                    {...this.props}
                />

                {/* 联查审批 */}
                <ApproveDetail
                    show={this.state.isApproveDetailShowed}
                    close={() => this.setState({ isApproveDetailShowed: false })}
                    {...this.state.approveDetailSourceData}
                />
            </div>
        );
    }
}

export default createPage({
    // billinfo: {
    //     billtype: 'grid',
    //     pagecode: config.pagecode,
    //     headcode: config.headcode
    // },
    mutiLangCode: config.mutiLangCode,
    initTemplate: null
})(Page);
